package com.yupi.yupicturebackend.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.*;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.yupi.yupicturebackend.config.CosClientConfig;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import com.yupi.yupicturebackend.manager.CosManager;
import com.yupi.yupicturebackend.model.dto.picture.PictureUploadRequest;
import com.yupi.yupicturebackend.model.dto.picture.UploadPictureResult;
import com.yupi.yupicturebackend.model.entity.Picture;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 之前虽然我们已经编写了通用的对象存储操作类 CosManager，但这个类并不能直接满足我们的图片上传需求。
 * 比如：
 * 图片是否符合要求？需要校验
 * 将图片上传到哪里？需要指定路径
 * 如何解析图片？需要使用数据万象服务
 */
@Slf4j
/**
 * 文件服务
 * @deprecated 已废弃，改为使用 upload 包的模板方法优化
 */
@Deprecated
public class FileManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;


    public UploadPictureResult uploadPictureResult(MultipartFile multipartFile, String uploadPathPrefix){

        // 1. 校验图片 大小 格式
        validPicture(multipartFile);
        // 2. 构造上传图路径 /前缀/日期+uuid+文件名.文件格式
        String originalFilename = multipartFile.getOriginalFilename();
        String uuid = RandomUtil.randomString(16);
        String fileSuffix = FileUtil.getSuffix(originalFilename);
        String date = DateUtil.formatDate(new Date());
        String uploadFilename = String.format("%s_%s.%s", date, uuid, fileSuffix);

        String uploadFilepath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);
        // 3. 上传到COS
        File tempFile = null;
        try {
            // 3.1. 创建临时文件
            tempFile = File.createTempFile(uploadFilepath, null);
            multipartFile.transferTo(tempFile); // 将 multipartFile 传输到临时文件
            // 3.2. 上传文件 获取到图片信息
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadFilepath, tempFile);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo(); // 获取图片信息
            // 3.3. 构造返回对象
            // 3.3.1. 计算图片宽高比
            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            double scale = (picWidth * 1.0 / picHeight);
            // 3.3.2 构造返回对象
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            uploadPictureResult.setUrl(cosClientConfig.getHost() + uploadFilepath);
            uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
            uploadPictureResult.setPicSize(FileUtil.size(tempFile));
            uploadPictureResult.setPicWidth(picWidth);
            uploadPictureResult.setPicHeight(picHeight);
            uploadPictureResult.setPicScale(scale);
            uploadPictureResult.setPicFormat(fileSuffix);
            return uploadPictureResult;
        } catch (Exception e) {
            log.error("图片上传失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "图片上传失败");
        } finally {
            if (tempFile != null){
                boolean delete = tempFile.delete();
                if (!delete){
                    log.error("图片删除失败 uploadFilepath = {}", uploadFilepath);
                }
            }
        }
    }

    public UploadPictureResult uploadPictureByUrl(String fileUrl, String uploadPathPrefix){

        //todo 1. 校验图片 大小 格式
        //validPicture(multipartFile);
        validPicture(fileUrl);
        //todo 2. 构造上传图路径 /前缀/日期+uuid+文件名.文件格式
        String uuid = RandomUtil.randomString(16);
        String originalFilename = FileUtil.mainName(fileUrl);
        String fileSuffix = FileUtil.getSuffix(originalFilename);
        String date = DateUtil.formatDate(new Date());
        String uploadFilename = String.format("%s_%s.%s", date, uuid, fileSuffix);

        String uploadFilepath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);
        // 3. 上传到COS
        File tempFile = null;
        try {
            // 3.1. 创建临时文件
            tempFile = File.createTempFile(uploadFilepath, null);
            // multipartFile.transferTo(tempFile); // 将 multipartFile 传输到临时文件
            HttpUtil.downloadFile(fileUrl, tempFile);
            // 3.2. 上传文件 获取到图片信息
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadFilepath, tempFile);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo(); // 获取图片信息
            // 3.3. 构造返回对象
            // 3.3.1. 计算图片宽高比
            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            double scale = (picWidth * 1.0 / picHeight);
            // 3.3.2 构造返回对象
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            uploadPictureResult.setUrl(cosClientConfig.getHost() + uploadFilepath);
            uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
            uploadPictureResult.setPicSize(FileUtil.size(tempFile));
            uploadPictureResult.setPicWidth(picWidth);
            uploadPictureResult.setPicHeight(picHeight);
            uploadPictureResult.setPicScale(scale);
            uploadPictureResult.setPicFormat(fileSuffix);
            return uploadPictureResult;
        } catch (Exception e) {
            log.error("图片上传到存储对象失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "图片上传失败");
        } finally {
            if (tempFile != null){
                boolean delete = tempFile.delete();
                if (!delete){
                    log.error("图片删除失败 uploadFilepath = {}", uploadFilepath);
                }
            }
        }
    }

    private void validPicture(String fileUrl) {
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "文件地址不能为空");
        // 1. 校验 url 格式
        try {
            new URL(fileUrl); // 能正确创建对象说明 url 合法
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件格式不正确");
        }
        // 2. 校验 url 协议
        ThrowUtils.throwIf(
                !fileUrl.startsWith("http://") || !fileUrl.startsWith("https://"),
                ErrorCode.PARAMS_ERROR,
                "仅支持 HTTP 或 HTTPS 协议的文件地址");
        // 3. 发送 HEAD 请求来验证文件是否存在
        HttpResponse response = null;
        try {
            response = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
            // 未正确返回，则无需进行其它校验
            if (response.getStatus() != HttpStatus.HTTP_OK){
                return;
            }
            // 4. 检验文件类型
            String contentType = response.header("Content-Type");
            if (StrUtil.isNotBlank(contentType)){
                final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("image/jpeg", "image/jpg", "image/webp");
                ThrowUtils.throwIf(!ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase()), ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
            // 5.校验文件大小
            String contentLengthStr = response.header("Content-Length");
            if (StrUtil.isNotBlank(contentLengthStr)){
                try {
                    long contentLength = Long.parseLong(contentLengthStr);
                    final long ONE_MB = 1024 * 1024;
                    ThrowUtils.throwIf(ONE_MB * 10 < contentLength, ErrorCode.PARAMS_ERROR, "文件不能超过10MB");
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
                }
            }
        } finally {
            if (response != null){
                response.close();
            }
        }


    }

    /**
     * 校验文件
     * @param multipartFile 传输文件
     */
    public void validPicture(MultipartFile multipartFile) {
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "上传图片为空");
        // 1. 图片大小
        long size = multipartFile.getSize();
        final long ONE_MB = 1024 * 1024;
        ThrowUtils.throwIf(ONE_MB * 10 < size, ErrorCode.PARAMS_ERROR, "文件不能超过10MB");
        // 2. 校验文件后缀 文件后缀用list集合存储
        final List<String> ALLOW_FORMAT_LIST = List.of("jpg","png","jpeg","webp");
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(fileSuffix), ErrorCode.PARAMS_ERROR, "只支持 jpg, png, jpeg, webp格式");
    }


}
